package socket1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @description:
 * @author: jhy
 * @time: 2021/4/17 15:02
 */


//Socket通信的服务端
public class ServerSocketDemo {

    public static void main(String[] args) throws IOException {

        //1.Socket的服务端，在本机的9999端口监听，等待服务端建立连接(要求本机没有占用9999端口)
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端在9999端口监听，等待客户端连接");

        //2.当没有客户端连接9999端口时，程序会阻塞，直到有客户端建立连接
        //当有客户端建立连接，返回一个Socket对象
        //多个(不同客户端)建立连接，返回不同的Socket对象
        Socket socket = serverSocket.accept();

        //3.通过socket.getInputStream()得到和socket相关的输入流对象,读取客户端写入到数据通道的数据，进行显示
        InputStream inputStream = socket.getInputStream();

        //4.IO读取
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(buf) )!= -1){//如果readLen(读取长度)等于-1，表明读取结束
                System.out.println(new String(buf,0,readLen));
        }

        //服务端接收到消息后，给客户端回复一个消息
        //得到与socket相关的输出流
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello client".getBytes());
        //设置输入结束标志
        socket.shutdownOutput();

        //6.关闭流和socket
        outputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
        System.out.println("服务端退出");

    }
}
